import SYCM from "~/utils/ali/sycm";
import {SycmTableUtils} from "~/utils/sycm/SycmTableUtils";
import Trans from "~/utils/sycm/trans";

export interface SYCMItem {
    itemId: string;
    detailUrl: string;
    pictUrl: string;
    title: string;
    trendData?: SYCMItemTrendData[];
    FlowTableData?: SycmItemAnalysisFlowRow[];
    keywordTableData?: SycmItemKeywordsTableData[];
}

export interface SycmItemAnalysisFlowRow {
    pageId: string;
    pPageId: string;
    pageName: string;
    pageName1: string;
    pageName2: string | null;
    pageName3: string | null;
    pageLevel: number;
    PayAmt: { cycleCrc?: number; value?: number };
    PayByrCnt: { cycleCrc?: number; value?: number };
    PayByrCntIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    PayRate: { cycleCrc?: number; value?: number };
    PayRateIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    TradeIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    Uv: { cycleCrc?: number; value?: number };
    UvIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    showDesc: boolean;
    uvValue: string;
    customerPrice: string;
}

export interface SycmItemKeywordsTableData {
    keyword: { value: string };
    uv?: { value: number | null };
    tradeIndex?: { value: number | null };
    uvValue?: { value: number | null };
}

export interface SYCMItemTrendData {
    // 日期
    date: string;
    // 日期
    fullDate: string;
    // 加购
    cartHits: number,
    // 收藏
    cltHits: number,
    // 支付件数
    payItemCnt: number,
    // 购买人数
    payByrCnt: number,
    // 支付转化率
    payRateIndex: number,
    // 搜索流量
    seIpvUvHits: number,
    // 搜索占比
    searchRate: number,
    // 交易额
    tradeIndex: number,
    // 访客数
    uvIndex: number,
    // 收藏率
    collectionRate: number,
    // 加购率
    addCartRate: number,
    // 总收藏加购人数
    collectionAddCart: number,
    // 客单价
    customerPrice: number,
    // UV价值
    uvValue: number,
    // 收藏加购率
    collectionAddCartRate: number,
}

export interface SYCMItemLists {
    item?: SYCMItem | null;
    item1?: SYCMItem | null;
    item2?: SYCMItem | null;
    _data: any;
}

export class SycmItemMonitor {
    // 获取竞品识别数据 - 竞品分析 获取竞品
    static async getItems() {
        let data: any = await SYCM.getInternalFiberData('[id^=__qiankun_microapp_wrapper_for_op_mc_] .sycm-mc-ci-item-analysis', 'memoizedProps.children[0]._owner.memoizedProps');
        let items: SYCMItemLists = {
            _data: data,
        };
        if (typeof data.selfItem !== 'undefined' && data.selfItem !== null) {
            items.item = {
                itemId: data.selfItem.item.itemId,
                detailUrl: data.selfItem.item.detailUrl,
                pictUrl: data.selfItem.item.pictUrl,
                title: data.selfItem.item.title,
            };
        }
        if (typeof data.rivalItem1 !== 'undefined' && data.rivalItem1 !== null) {
            items.item1 = {
                itemId: data.rivalItem1.item.itemId,
                detailUrl: data.rivalItem1.item.linkUrl,
                pictUrl: data.rivalItem1.item.picUrl,
                title: data.rivalItem1.item.name,
            };
        }
        if (typeof data.rivalItem2 !== 'undefined' && data.rivalItem2 !== null) {
            items.item2 = {
                itemId: data.rivalItem2.item.itemId,
                detailUrl: data.rivalItem2.item.linkUrl,
                pictUrl: data.rivalItem2.item.picUrl,
                title: data.rivalItem2.item.name,
            };
        }
        return items;
    }

    // 获取竞品识别数据 - 竞品分析 入店搜索词
    static async assignItemsKeywordTableData(items: SYCMItemLists | null) {
        const data = items?._data;
        if (typeof data['sycm-mc-ci-item-analysis-keyword-table-flow-selfItem'] == 'undefined' || data['sycm-mc-ci-item-analysis-keyword-table-flow-selfItem'] == null) {
            // @ts-ignore
            document.querySelector("#sycm-mc-ci-item-analysis-keyword > div.oui-card-header-wrapper > div.oui-card-header > div.oui-card-header-item.oui-card-header-item-pull-left > span > span.oui-tab-switch-item:nth-child(1)").click();
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    resolve(this.assignItemsKeywordTableData(await this.getItems()));
                }, 500);
            });
        }
        if (typeof data['sycm-mc-ci-item-analysis-keyword-table-trade-selfItem'] == 'undefined' || data['sycm-mc-ci-item-analysis-keyword-table-trade-selfItem'] == null) {
            // @ts-ignore
            document.querySelector("#sycm-mc-ci-item-analysis-keyword > div.oui-card-header-wrapper > div.oui-card-header > div.oui-card-header-item.oui-card-header-item-pull-left > span > span.oui-tab-switch-item:nth-child(2)").click();
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    resolve(this.assignItemsKeywordTableData(await this.getItems()));
                }, 500);
            });
        }
        if (items?.item) {
            items.item.keywordTableData = [];
            items.item = await this.assignItemKeywordTableData(items.item, items._data, 1);
        }
        if (items?.item1) {
            items.item1.keywordTableData = [];
            items.item1 = await this.assignItemKeywordTableData(items.item1, items._data, 2);
        }
        if (items?.item2) {
            items.item2.keywordTableData = [];
            items.item2 = await this.assignItemKeywordTableData(items.item2, items._data, 3);
        }
        return items;
    }

    private static async assignItemKeywordTableData(item: SYCMItem, data: any, type: number = 1) {
        let prefix: string = 'selfItem';
        if (type === 2) {
            prefix = 'rivalItem1';
        } else if (type === 3) {
            prefix = 'rivalItem2';
        }
        const flowTable = data['sycm-mc-ci-item-analysis-keyword-table-flow-' + prefix]['originalTableData']['data'];
        const tradeTable = data['sycm-mc-ci-item-analysis-keyword-table-trade-' + prefix]['originalTableData']['data'];
        const keywordTableData: SycmItemKeywordsTableData[] = [];
        flowTable.forEach((it: any) => {
            const keyword: SycmItemKeywordsTableData = {
                keyword: {value: it.keyword.value},
                uv: {value: it.uv.value},
                tradeIndex: {value: null},
                uvValue: {value: null},
            };
            keywordTableData.push(keyword);
        });
        tradeTable.forEach((it: any) => {
            // 如果keyword 已经存在
            const index = keywordTableData.findIndex((item: SycmItemKeywordsTableData) => {
                return item.keyword.value === it.keyword.value;
            });
            if (index !== -1) {
                keywordTableData[index].tradeIndex = {value: it.tradeIndex.value};
                // @ts-ignore
                keywordTableData[index].uvValue = {value: parseFloat((Trans.number(it.tradeIndex.value) / keywordTableData[index].uv?.value || 0).toFixed(2))};
            } else {
                const keyword: SycmItemKeywordsTableData = {
                    keyword: {value: it.keyword.value},
                    uv: {value: null},
                    tradeIndex: {value: it.tradeIndex.value},
                    uvValue: {value: null},
                };
                keywordTableData.push(keyword);
            }
        })
        item.keywordTableData = keywordTableData;
        return item;
    }

    static async assignItemTrendData(items: SYCMItemLists | null) {
        if (!items) {
            return null;
        }
        const data = await SYCM.getInternalFiberData('#sycm-mc-ci-item-analysis-trend > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content > div > div.alife-one-design-sycm-indexes-trend-chart-container .oui-pro-composed-chart', 'memoizedProps.children.props.children.props.data');
        const assignItemTrendData = (item: SYCMItem, dataItem: any | null, type: number) => {
            let pix: string = 'selfItem';
            if (type === 2) {
                pix = 'rivalItem1';
            } else if (type === 3) {
                pix = 'rivalItem2';
            }

            const collectionRate = parseFloat((Trans.number(dataItem[pix + 'CltHits']) / Trans.number(dataItem[pix + 'UvIndex'])).toFixed(4));
            const addCartRate = parseFloat((Trans.number(dataItem[pix + 'CartHits']) / Trans.number(dataItem[pix + 'UvIndex'])).toFixed(4));
            const payByrCnt = Math.round((Trans.ratio(dataItem[pix + 'PayRateIndex']).replaceAll('%', '') / 100) * Trans.number(dataItem[pix + 'UvIndex']));
            let trendData: SYCMItemTrendData = {
                date: dataItem.date,
                fullDate: dataItem.fullDate,
                cartHits: dataItem[pix + 'CartHits'],
                cltHits: dataItem[pix + 'CltHits'],
                payItemCnt: dataItem[pix + 'PayItemCnt'],
                payRateIndex: dataItem[pix + 'PayRateIndex'],
                payByrCnt: payByrCnt,
                seIpvUvHits: dataItem[pix + 'SeIpvUvHits'],
                searchRate: parseFloat((Trans.number(dataItem[pix + 'SeIpvUvHits']) / Trans.number(dataItem[pix + 'UvIndex'])).toFixed(4)) || 0.0000,
                tradeIndex: dataItem[pix + 'TradeIndex'],
                uvIndex: dataItem[pix + 'UvIndex'],
                collectionRate: collectionRate || 0.0000,
                addCartRate: addCartRate || 0.0000,
                collectionAddCart: (Trans.number(dataItem[pix + 'CartHits']) + Trans.number(dataItem[pix + 'CltHits'])) || 0,
                customerPrice: (parseFloat(String((Trans.number(dataItem[pix + 'TradeIndex']) / payByrCnt).toFixed(2)))) || 0.00,
                uvValue: (parseFloat((Trans.number(dataItem[pix + 'TradeIndex']) / Trans.number(dataItem[pix + 'UvIndex'])).toFixed(2))) || 0.00,
                collectionAddCartRate: (collectionRate + addCartRate) || 0.00,
            };
            item.trendData?.push(trendData);
            return item;
        };
        data.map((item: any) => {
            if (items.item) {
                if (typeof items.item.trendData === 'undefined' || items.item.trendData === null) {
                    items.item.trendData = [];
                }
                items.item = assignItemTrendData(items.item, item, 1);
            }
            if (items.item1) {
                if (typeof items.item1.trendData === 'undefined' || items.item1.trendData === null) {
                    items.item1.trendData = [];
                }
                items.item1 = assignItemTrendData(items.item1, item, 2);
            }
            if (items.item2) {
                if (typeof items.item2.trendData === 'undefined' || items.item2.trendData === null) {
                    items.item2.trendData = [];
                }
                items.item2 = assignItemTrendData(items.item2, item, 3);
            }
        });
        return items;
    }

    static async getMonitorLists() {
        let data = await SYCM.getInternalFiberData('#completeItem > div.oui-card-content', 'memoizedProps.children._owner.memoizedProps[\'sycm-mc-ci-item-monitor\'].originalTableData.data');
        // console.log(data.data);
        data.data.forEach((item: any) => {
            // 支付转化率
            if (item.payRateIndex === 0 || item.uvIndex === 0) {
                item.payRate = 0;
            } else {
                item.payRate = Trans.ratio(item.payRateIndex.value).replaceAll('%', '') / 100;
            }
            // 计算访客数
            if (item.uvIndex === 0 || item.payRateIndex === 0) {
                item.uv = 0;
            } else {
                item.uv = Trans.number(item.uvIndex.value).toFixed(0);
            }
            // 搜索占比
            if (item.seIpvUvHits === 0 || item.uvIndex === 0) {
                item.searchRate = 0;
            } else {
                item.searchRate = (Trans.number(item.seIpvUvHits.value) / Trans.number(item.uvIndex.value)).toFixed(4);
            }
            // 计算支付买家数
            if (item.uvIndex === 0 || item.payRateIndex === 0) {
                item.payBuyer = 0;
            } else {
                item.payBuyer = (item.uv * item.payRate).toFixed(0);
            }
            // 计算客单价
            if (item.tradeIndex === 0 || item.uvIndex === 0 || item.visitor === 0) {
                item.customerPrice = 0;
            } else {
                item.customerPrice = (parseFloat(SycmTableUtils.tranNumber(false, item.tradeIndex.value, 2, false)) / item.payBuyer).toFixed(2);
            }
            // 计算UV价值
            if (item.uvIndex === 0) {
                item.uvValue = 0;
            } else {
                item.uvValue = (SycmTableUtils.tranNumber(false, item.tradeIndex.value, 2, false) / SycmTableUtils.tranNumber(false, item.uvIndex.value, 2)).toFixed(2);
            }
            // 计算收藏率
            if (item.uvIndex === 0 || item.cltHits === 0) {
                item.collectionRate = 0;
            } else {
                item.collectionRate = (Trans.number(item.cltHits.value) / item.uv).toFixed(4);
            }
            // 计算加购率
            if (item.uvIndex === 0 || item.cartHits === 0) {
                item.addCartRate = 0;
            } else {
                item.addCartRate = (Trans.number(item.cartHits.value) / item.uv).toFixed(4);
            }
            // 总收藏加购人数
            if (item.cltHits === 0 || item.cartHits.value === 0) {
                item.collectionAddCart = 0;
            } else {
                item.collectionAddCart = Trans.number(item.cltHits.value) + Trans.number(item.cartHits.value);
            }
            // 收藏加购率
            if (item.uvIndex === 0 || item.collectionAddCart === 0) {
                item.collectionAddCartRate = 0;
            } else {
                item.collectionAddCartRate = (parseFloat(item.collectionRate) + parseFloat(item.addCartRate)).toFixed(4);
            }
        });
        return data;
    }

    // 获取竞品识别数据 - 浏览流失
    static getCompetitiveIdentificationFlowAway() {
        return SYCM.getInternalFiberData('#sycm-mc-ci-item-recognition-custom > div.oui-card-content', 'memoizedProps.children._owner.memoizedProps.originalTableData');
    }

    // 获取竞品识别数据 - 搜索流失
    static getCompetitiveIdentificationSearchAway() {
        return SYCM.getInternalFiberData('#sycm-mc-ci-item-recognition-search .oui-card-content', 'memoizedProps.children._owner.memoizedProps.originalTableData');
    }

    // 获取竞品流量分析
    static async assignItemListFlowTable(items: SYCMItemLists): Promise<SYCMItemLists> {
        const data = items._data['sycm-mc-ci-item-analysis-flow-source-new']['tableData']['data'];
        // if (typeof data === 'undefined' || !data) {
        //     return new Promise((resolve, reject) => {
        //         setTimeout(() => {
        //             resolve(this.assignItemListFlowTable(items));
        //         }, 1000);
        //     });
        // }
        if (items.item) {
            items.item.FlowTableData = [];
            data.map(async (it: any) => {
                items.item = await this.assignItemFlowTable(items.item, 1, it);
            });
        }
        if (items.item1) {
            items.item1.FlowTableData = [];
            data.map(async (it: any) => {
                items.item1 = await this.assignItemFlowTable(items.item1, 2, it);
            });
        }
        if (items.item2) {
            items.item2.FlowTableData = [];
            data.map(async (it: any) => {
                items.item2 = await this.assignItemFlowTable(items.item2, 3, it);
            });
        }
        return items;
    }

    private static async assignItemFlowTable(item: SYCMItem | null | undefined, type: number, data: any, indexes: number[] = [], pageNames: string[] = []): Promise<SYCMItem | null | undefined> {
        let keyPrefix: string = 'selfItem';
        if (type === 2) {
            keyPrefix = 'rivalItem1';
        } else if (type === 3) {
            keyPrefix = 'rivalItem2';
        }

        let d: any;
        if (indexes.length === 0) {
            d = JSON.parse(JSON.stringify(data));
        } else if (indexes.length === 1) {
            d = JSON.parse(JSON.stringify(data.children[indexes[0]]));
        } else if (indexes.length === 2) {
            d = JSON.parse(JSON.stringify(data.children[indexes[0]].children[indexes[1]]));
        } else if (indexes.length === 3) {
            d = JSON.parse(JSON.stringify(data.children[indexes[0]].children[indexes[1]].children[indexes[2]]));
        }
        if (typeof item !== 'undefined' && typeof item?.FlowTableData === 'undefined') {
            // @ts-ignore
            item.FlowTableData = [];
        }
        console.log(d);
        pageNames.push(d.pageName.value);
        let customerPrice = '0.00';
        if (typeof d[keyPrefix + 'TradeIndex'] !== 'undefined' && typeof d[keyPrefix + 'TradeIndex'].value !== 'undefined' &&
            typeof d[keyPrefix + 'PayByrCntIndex'] !== 'undefined' && typeof d[keyPrefix + 'PayByrCntIndex'].value !== 'undefined') {
            customerPrice = (Trans.number(d[keyPrefix + 'TradeIndex'].value) / Trans.number(d[keyPrefix + 'PayByrCntIndex'].value || 0)).toFixed(2);
            if (customerPrice === 'NaN') {
                customerPrice = '0.00';
            }
        }
        let uvValue = '0.00';
        if (typeof d[keyPrefix + 'TradeIndex'] !== 'undefined' && typeof d[keyPrefix + 'TradeIndex'].value !== 'undefined' &&
            typeof typeof d[keyPrefix + 'UvIndex'] !== 'undefined' && typeof d[keyPrefix + 'UvIndex'].value !== 'undefined') {
            uvValue = (Trans.number((d[keyPrefix + 'TradeIndex'].value || 0)) / Trans.number(d[keyPrefix + 'UvIndex'].value || 0)).toFixed(2);
            if (uvValue === 'NaN') {
                uvValue = '0.00';
            }
        }
        // @ts-ignore
        item?.FlowTableData.push({
            pageName1: pageNames[0],
            pageName2: pageNames[1] || null,
            pageName3: pageNames[2] || null,
            PayAmt: {...d[keyPrefix + 'PayAmt']},
            PayByrCnt: {...d[keyPrefix + 'PayByrCnt']},
            PayByrCntIndex: {...d[keyPrefix + 'PayByrCntIndex']},
            PayRate: {...d[keyPrefix + 'PayRate']},
            PayRateIndex: {...d[keyPrefix + 'PayRateIndex']},
            TradeIndex: {...d[keyPrefix + 'TradeIndex']},
            Uv: {...d[keyPrefix + 'Uv']},
            UvIndex: {...d[keyPrefix + 'UvIndex']},
            pageLevel: indexes.length,
            pageName: d.pageName.value,
            showDesc: d.showDesc.value === 1,
            pageId: d.pageId.value,
            pPageId: d.pPageId.value,
            customerPrice: customerPrice,
            uvValue: uvValue,
        });

        if (typeof d.children !== 'undefined') {
            for (const it of d.children) {
                const index: number = d.children.indexOf(it);
                item = await this.assignItemFlowTable(item, type, data, [...indexes, index], [...pageNames]);
            }
        }
        // item.TopTable = d;
        return item;
    }
}
